package com.icangya.Utils.httpsRequest;

import org.json.JSONObject;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

public class PqTest {
//    public static void main(String[] args) {
//        String url="https://127.0.0.1:8080/openNozzle";
//        String a = "aaaaaa";
//        System.out.println(sendHtpps(a,url));
//    }

    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String sendHtpps(Map<String, String> data,String url) {
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn;
        try {
            trustAllHosts();
            URL realUrl = new URL(url);
            //通过请求地址判断请求类型(http或者是https)
            if (realUrl.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();

            }
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//            conn.setRequestProperty("Cache-Control", "no-cache");
//            conn.setReadTimeout(5000);
//            conn.setConnectTimeout(5000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.connect();

            org.json.JSONObject jsonObject = new org.json.JSONObject(data);
//            StringBuffer queryBuffer = new StringBuffer();
//            for (Map.Entry<String, String> entry : data.entrySet()) {
//                queryBuffer.append(entry.getKey() + "=" + entry.getValue() + "&");
//            }
//            String queryStr = queryBuffer.substring(0, queryBuffer.length() - 1);
            Set<String> keySet = data.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            Arrays.sort(keyArray);
//            StringBuilder sb = new StringBuilder();
            for (String k : keyArray) {
                if (data.get(k).trim().length() > 0) {// 参数值为空，则不参与签名
//                    sb.append(k).append("=").append(data.get(k).trim()).append("&");
                    jsonObject.put(k,data.get(k).trim());
                }
            }
//          String queryStr = sb.substring(0, sb.length() - 1);

            String queryStr = String.valueOf(jsonObject);
            System.out.println("");
            System.out.println("1请求支付的参数："+jsonObject.toString());
            System.out.println("");

            PrintWriter writer = new PrintWriter(conn.getOutputStream());
            writer.write(queryStr);
            writer.flush();
            writer.close();
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader reader = new BufferedReader((new InputStreamReader(inputStream)));
                String line;
                String str = "";
                StringBuffer buffer = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    str += line;
                    buffer.append(line);
                }
                System.out.print(buffer.toString());
                System.out.println("");
                System.out.println("");
                return buffer.toString();
            }
//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(a);
//            // flush输出流的缓冲
//            out.flush();
//            // 定义BufferedReader输入流来读取URL的响应
//            in = new BufferedReader(
//                    new InputStreamReader(conn.getInputStream()));
//            String line;
//            while ((line = in.readLine()) != null) {
//                result += line;
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}